package ift605.EquationWithTrainingAgents.behavior.special.complex;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jade.core.AID;
import jade.lang.acl.ACLMessage;
import ift605.EquationWithAgent.server.EquationMessage;
import ift605.EquationWithTrainingAgents.agent.PoolAgent;
import ift605.EquationWithTrainingAgents.agent.TrainingAgentClient;
import ift605.EquationWithTrainingAgents.behavior.common.DeriverBehavior;
import ift605.EquationWithTrainingAgents.struct.DerivationInfo;
import ift605.EquationWithTrainingAgents.struct.PendingRequest;
import udes.ds.agent.AbstractEquation;

public class RequestDerivationBehavior extends DeriverBehavior 
{
	private static final long serialVersionUID = 1L;
	private int mNextRequest = 2000;
	
	@Override
	public boolean derive(List<DerivationInfo> aDerivationInfos)
	{
		try 
		{
			DerivationInfo info = aDerivationInfos.get(0);
			Object[] values = info.Mess.base.getValues();
			for(int i = 0; i < values.length; ++i)
			{
				if(values[i] instanceof AbstractEquation)
				{
					// Request a derivation
					AbstractEquation eq  = (AbstractEquation)values[i];					
					ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
					msg.setConversationId(EquationMessage.DERIVATE_ID);
					msg.setContentObject(new EquationMessage(mNextRequest, eq));
					msg.addReceiver(new AID(TrainingAgentClient.NEW_AID_NAME_DERIVATIVE, AID.ISLOCALNAME));
					myAgent.send(msg);
					
					//System.out.println("Awesome :: ask derivative for " + mNextRequest);
					
					PoolAgent casted = ((PoolAgent)myAgent);
					//save requestion in BD
					casted.mInProgess.put(String.valueOf(mNextRequest), new DerivationInfo(info.Mess,i));
					
					if(!casted.mEquationChunk.containsKey(info.Mess.requestID))
					{
						casted.mEquationChunk.put(info.Mess.requestID, new ArrayList<PendingRequest>());
					}
					casted.mEquationChunk.get(info.Mess.requestID).add( new PendingRequest(mNextRequest, false));
							
					// setup for next request
					mNextRequest++;
				}
			}
		}
		catch (IOException e) { 
			e.printStackTrace(); 
		}
		return false;
	}
}
